﻿using AOITest.utils;
using System.Configuration;
using System.Text;
using System.Text.RegularExpressions;
using AOITest.DataModels;
using Newtonsoft.Json;

namespace AOITest
{
    
    class  Program
    {

        private static readonly string Inputpath = ConfigurationManager.AppSettings["inputpath"]!;
        private static readonly string Outputpath = ConfigurationManager.AppSettings["outputpath"]!;
        private static readonly string Templatepath = ConfigurationManager.AppSettings["templatepath"]!;
        private static readonly string AcrivePath = ConfigurationManager.AppSettings["acrivePath"]!;
        private static readonly string N4188CPath = ConfigurationManager.AppSettings["jsonPath"]!;
        private static readonly string ExcelPath = ConfigurationManager.AppSettings["ExcelPath"]!;
        
        private static readonly string SharedFolderPath = ConfigurationManager.AppSettings["sharedFolderPath"]!;
        private static readonly string SharedFolderUser = ConfigurationManager.AppSettings["sharedFolderUser"]!;
        private static readonly string SharedFolderPassword = ConfigurationManager.AppSettings["sharedFolderPassword"]!;

        
        
        
        
        public static async Task Main(string[] args)
        {

            
            // var r = ToolUtils.Connect(SharedFolderPath, SharedFolderUser, SharedFolderPassword);
            //
            // Console.WriteLine(r);
            
            if (File.Exists(ExcelPath))
            {
                StringUtils.ConvertExcel(ExcelPath,N4188CPath);
            }

            if (!Directory.Exists(Inputpath))
            {
                LogHelper.Info("Input Directory doesn't exist!");
            }
            
            string[] files = Directory.GetFiles(Inputpath);

            if (files.Length == 0)
            {
                Console.WriteLine("没有文件！");
                
            }

            #region FDM注释
            // for (int i = 0; i < files.Length; i++)
            // {
            //     string filename = Path.GetFileNameWithoutExtension(files[i]);
            //     
            //     
            //     string outputPath = Path.Combine(@"C:\Users\wangyuxiang\Desktop\csv", $"{(i+1).ToString().PadLeft(3,'0')}."+ filename +".csv");
            //
            //     var parsed = TxtUtils.ParseAoiFile(files[i]);
            //     TxtUtils.ExportToCsv(parsed, outputPath);
            // }
            //
            // return;
            

            #endregion
            

            for (int i = 0; i < files.Length; i++)
            {
                string filename = Path.GetFileNameWithoutExtension(files[i]);

                // 获得 waferId,device,lotNo,slotNo 信息
                try
                {
                    var (waferId, productId, lotNo, slotNo) = await GetLotInfo(files[i]);
                    

                    if (filename.Contains("DPAT"))
                    {
                         (waferId, productId, lotNo, slotNo)= await TxtUtils.GetLotInfoTxt(files[i]);
                         
                    }
                    
                    
                    string vegaPath = Path.Combine(Outputpath, lotNo);
                    
                    if (productId == "YSZ316BR0002" || productId == "YSZ316BR0006" || productId == "Y0TS10BR0012" || productId == "Y0TS10BR0015" || productId == "YSZ316BR0003" || productId == "ZSZ3160009"|| productId == "ZSZ3160008" || productId == "YSZ316BR0006-F1")
                    {
                        
                        waferId = waferId.Replace(lotNo, "");
                        slotNo = int.Parse(waferId);
                       
                    }

                    if (productId == "YSH589BR0001")
                    {
                        lotNo = filename.Split("#")[0];
                        string hahah = filename.Substring(filename.IndexOf('#') + 1, 2);
                        slotNo = int.Parse(hahah);
                    }
                    
                    
                    if (!Directory.Exists(vegaPath))
                    {
                        Directory.CreateDirectory(vegaPath);
                    }
                    
                    
                        
                    // 找到模板dat文件
                    string templateDatPath = Path.Combine(Templatepath, productId + ".dat");

                    string formateSlotNo = slotNo.ToString("000");
                    
                    // 输出文件名
                    
                    string outputFile = String.Empty; 

                    if (productId.Contains("N41881C") || productId == "N46307B")
                    {
                        // N41881C N46307B
                         outputFile = Path.Combine(Outputpath, lotNo, formateSlotNo + "." + waferId.Trim().ToUpper());
                         
                    }
                    else if (productId.Contains("N81295") || productId == "NQ9140" || productId == "N63881" || productId == "NQ9140B" || productId == "N81739")
                    {
                        // N81295/N81295/N81295D4

                        string checkId = StringUtils.GenerateCheckCode(lotNo, waferId,true,false);
                        string tempLotNo = String.Empty;
                        if (productId.Contains("NQ9140") ||  productId == "N63881" || productId == "NQ9140B" )
                        {
                            tempLotNo = lotNo.Split('.')[0];
                            checkId = StringUtils.GenerateCheckCode(tempLotNo, waferId, true,true);
                            if (productId == "NQ9140B")
                            {
                                checkId = checkId.Replace("-", ".");
                            }
                            
                        }
                        
                        outputFile = Path.Combine(Outputpath, lotNo, checkId); // PPS861

                    }
                    // N61295 N62881C
                    else if ( productId == "N62881C" || productId == "N62881D" )
                    {
                      // string checkId = StringUtils.GenerateCheckCode(lotNo.Substring(0,lotNo.IndexOf(".", StringComparison.Ordinal)),waferId);
                        
                        outputFile = Path.Combine(Outputpath, lotNo, formateSlotNo + "." + waferId.Trim().ToUpper());
                    }
                    else if (productId == "SCWX901A3")
                    {
                        outputFile = Path.Combine(Outputpath, lotNo,lotNo + "-" + waferId);
                        
                    }else if (productId == "N61598C")
                    {
                        string checkId = StringUtils.GenerateCheckCode(lotNo, waferId,false,false);
                        outputFile = Path.Combine(Outputpath, lotNo, checkId); 
                    }
                    else if (productId == "N61295" )
                    {
                         string checkId = StringUtils.GenerateCheckCode(lotNo, waferId,false,false);
                        outputFile = Path.Combine(Outputpath, lotNo, checkId); 
                    }
                    else if (productId == "MBD602QA" || productId == "H1752"  || productId == "H2305BTAC1-000F000" || productId == "H2305CTAC1-000F000" || productId == "H2305DTAC1-000F000")
                    {
                        outputFile = Path.Combine(Outputpath, lotNo, formateSlotNo + "." + lotNo + "-"+ waferId.Trim().ToUpper());
                    }
                    else if (productId == "YSZ316BR0002" || productId == "YSZ316BR0006" || productId == "Y0TS10BR0012" || productId == "YSZ316BR0003" || productId == "YSZ316BR0006-F1" || productId == "Y0TS10BR0015")
                    {
                        outputFile = Path.Combine(Outputpath, lotNo, formateSlotNo + "." + filename);
                    }
                    else if (productId == "TMUR55D")
                    {
                        outputFile = Path.Combine(Outputpath, lotNo, formateSlotNo + "." + lotNo + "_" + waferId);
                    }
                    else if (productId == "YSH589BR0001")
                    {
                        outputFile = Path.Combine(Outputpath, lotNo, formateSlotNo + "." + filename.Replace("#", "-"));
                    }
                    else
                    {
                        outputFile = Path.Combine(Outputpath, lotNo, formateSlotNo + "." + lotNo + "-" + waferId);

                    }


                    if (!File.Exists(templateDatPath))
                    {
                        List<string> mailReceiver = StringUtils.GetMailReceiver();   
                        string subject = "缺少对应的模板文件，请工程师确认！";
                        Console.WriteLine("缺少对应的模板文件，请工程师确认！");
                        MailHelper.SendMail(subject,templateDatPath,mailReceiver);
                    }
                    
                    
                    
                    if (File.Exists(templateDatPath) )  
                    {
                        bool isWrong = true;
                        
                        // 复制文件存档目录
                        string sourceFile = files[i];
                        string destinationFile = Path.Combine(AcrivePath, filename + ".txt");
                        File.Copy(sourceFile, destinationFile, true);
                        
                        // 用二进制方式打开模板dat文件
                        ReadDeviceMapResult deviceMapResult = ReadDeviceMap(templateDatPath);


                        #region 测试dat
                        // using (StreamWriter writer = new StreamWriter("D:\\RiderProjects\\aoitest\\AOITest\\vega\\aoitxt.txt"))
                        // {
                        //     for (int x = 0; x < deviceMapResult.testResult.GetLength(0); x++)
                        //     {
                        //         for (int y = 0; y < deviceMapResult.testResult.GetLength(1); y++)
                        //         {
                        //             writer.Write(deviceMapResult.testResult[x,y]);
                        //         }
                        //         await writer.WriteLineAsync("");
                        //     }
                        //     
                        // }
                        //
                        //
                        // using (StreamWriter writer = new StreamWriter("D:\\RiderProjects\\aoitest\\AOITest\\vega\\aoitxt1.txt"))
                        // {
                        //     for (int x = 0; x < deviceMapResult.categoryData.GetLength(0); x++)
                        //     {
                        //         for (int y = 0; y < deviceMapResult.categoryData.GetLength(1); y++)
                        //         {
                        //             writer.Write(deviceMapResult.categoryData[x, y]);
                        //         }
                        //         await writer.WriteLineAsync("");
                        //     }
                        //     
                        // }
                        #endregion
                        
                        
                        string name = $"{lotNo}{slotNo:00}";

                        if (!filename.Contains(name)) isWrong = false;

                        ReadTsnResult tsnResult;

                        if (productId == "MBD602QA")
                        {
                             tsnResult =TxtUtils.ReadTxtMap(files[i], deviceMapResult.newnumflat);
                        }
                        else if (productId == "H2305BTAC1-000F000" || productId == "H2305CTAC1-000F000" || productId == "H2305DTAC1-000F000")
                        {
                            tsnResult =TxtUtils.ReadTxtSzwMap(files[i], deviceMapResult.newnumflat);
                        }
                        else if (productId == "ASAW0741A_1" || productId == "ASAW0366A_1" 
                                                            || productId == "ASAW3940A_1" || productId == "ASAW0826E_1" 
                                                            || productId == "ASAW4041A_1" || productId == "ASAW3439D_1"  
                                                            || productId == "ASAW3439D_1_OPC" || productId == "ASAW3439D_2"
                                                            || productId == "ASAW0741B_1"  || productId == "ASAW036625E_1"
                                                            || productId == "ASAW404107C_1" || productId == "WSAW036625A_1" 
                                                            || productId == "ASAW0826F_1" || productId == "ASAW3940B_1")
                        {
                            tsnResult =TxtUtils.ReadTxtASAW0741A_1Map(files[i], deviceMapResult.newnumflat);
                        }
                        else if (productId == "H1752")
                        {
                            tsnResult =TxtUtils.ReadTxtSCWX810A3Map(files[i], deviceMapResult.newnumflat);
                        }
                        else if (productId == "YSZ316BR0002" || productId == "YSZ316BR0006" || productId == "Y0TS10BR0012" || productId == "YSZ316BR0003" || productId == "YSZ316BR0006-F1" || productId == "Y0TS10BR0015")
                        {
                            
                            tsnResult =TxtUtils.ReadYSZMap(files[i], deviceMapResult.newnumflat);
                        }
                        else if (productId == "FG-DHCJ-02574")
                        {
                            tsnResult =TxtUtils.ReadTxtMap_ALG(files[i], deviceMapResult.newnumflat);
                            
                        }
                        else if (productId == "U06A-AB1-1")
                        {
                            tsnResult =TxtUtils.ReadTxtMap_U06A(files[i], deviceMapResult.newnumflat);
                        }
                        else if (productId == "GM1V1" || productId == "GM1VJ" || productId == "G0RT6" ||productId == "G0RL3" || productId == "GM1WE" || productId== "GM1V0")
                        {
                            tsnResult = TxtUtils.ReadTxtGM1V1Map(files[i], deviceMapResult.newnumflat,productId);
                        }
                        else if (productId == "YSH589BR0001")
                        {
                            tsnResult = TxtUtils.ReadTxtYSH589BR0001Map(files[i], deviceMapResult.newnumflat);
                        }
                        else if (productId == "ZSZ3160009" || productId == "ZSZ3160008" || productId == "FX266RB5103W")
                        {
                            tsnResult = TxtUtils.ReadTxtZSZ3160009Map(files[i], deviceMapResult.newnumflat);
                        }
                        else
                        {
                            // 读取tsn客户的AOI文件
                             tsnResult = ReadTsn2Map(files[i],deviceMapResult.newnumflat);
                        }
                        
                        // ================  TODO 注意这里的startRow 和  startCol ================
                        // ================  TODO 还要注意这个里的[sRow-1 , sCol-1 ] N41881C和 N46307B 这里要减 - ===========
                        
                        
                        for (int x = 0; x < deviceMapResult.testResult.GetLength(0); x++)
                        {
                            for (int y = 0; y < deviceMapResult.testResult.GetLength(1); y++)
                            {
                                deviceMapResult.testResult[x, y] = 0;
                            }
                        }
                        
                        
                        for (int x = 0; x < deviceMapResult.categoryData.GetLength(0); x++)
                        {
                            for (int y = 0; y < deviceMapResult.categoryData.GetLength(1); y++)
                            {
                                deviceMapResult.categoryData[x, y] = 0;
                            }
                        }

                        if (tsnResult.product_id == "N46309")
                        {
                            for (int sRow = 3; sRow <= 216; sRow++)
                            {
                                for (int sCol = 3; sCol <= 226; sCol++)
                                {
                                    deviceMapResult.testResult[sRow , sCol ] = tsnResult.AOIMapData[sRow-2 , sCol-2 ];
                                    deviceMapResult.categoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow-2 , sCol-2];
                                    
                                    // deviceMapResult.testResult[3, 102 ] = 2;   1  100
                                    // deviceMapResult.categoryData[3  , 102] = 59;
                                    if (deviceMapResult.isExtRes == "1")
                                    {
                                        deviceMapResult.excategoryData[sRow , sCol] = tsnResult.AOIMapCategory[sRow-2,sCol-2].ToString();
                                    }
                                
                                }
                            }
                        }
                        else if (tsnResult.product_id == "FG-DHCJ-02574")
                        {
                           // 1 24   1,24
                           for (int sRow = 0; sRow <= 73; sRow++)
                           {
                               for (int sCol = 0; sCol <= 59; sCol++)
                               {
                                   try
                                   {
                                       deviceMapResult.testResult[sRow, sCol] = tsnResult.AOIMapData[sRow , sCol ];
                                       deviceMapResult.categoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow , sCol ];
                                       
                                       if (deviceMapResult.isExtRes == "1")
                                       {
                                           deviceMapResult.excategoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow , sCol ].ToString();
                                       }
                                   }catch (Exception ex)
                                   {
                                       Console.WriteLine(ex.Message);
                                       Console.WriteLine($"row === {sRow} col === {sCol}");
                                   }
                               }
                           }

                           
                           
                        }
                        else if (tsnResult.product_id == "MBD602QA")
                        {
                            for (int sRow = 1; sRow <= 107; sRow++)
                            {
                                for (int sCol = 1; sCol <= 71; sCol++)
                                {
                                
                                    deviceMapResult.testResult[sRow-1 , sCol-1 ] = tsnResult.AOIMapData[sRow , sCol ];
                                    deviceMapResult.categoryData[sRow-1 , sCol-1] = tsnResult.AOIMapCategory[sRow , sCol];
                                
                                    // deviceMapResult.testResult[3 -1, 31-1 ] = 2;
                                    // deviceMapResult.categoryData[3-1  , 31-1] = 7;
                                    if (deviceMapResult.isExtRes == "1")
                                    {
                                        deviceMapResult.excategoryData[sRow-1 , sCol-1] = tsnResult.AOIMapCategory[sRow,sCol].ToString();
                                    }
                                
                                }
                            }
                        }
                        else if (tsnResult.product_id == "H2305BTAC1-000F000" || tsnResult.product_id == "H2305CTAC1-000F000" || tsnResult.product_id == "H2305DTAC1-000F000")
                        {
                            for (int sRow = 3; sRow <= 249; sRow++)
                            {
                                for (int sCol = 3; sCol <= 249; sCol++)
                                {
                                
                                    deviceMapResult.testResult[sRow, sCol ] = tsnResult.AOIMapData[sRow-2 , sCol-2 ];
                                    deviceMapResult.categoryData[sRow , sCol] = tsnResult.AOIMapCategory[sRow-2 , sCol-2];
                                    
                                    // deviceMapResult.testResult[3 , 113] = 2;
                                    // deviceMapResult.categoryData[3 , 113] = 7;
                                    if (deviceMapResult.isExtRes == "1")
                                    {
                                        deviceMapResult.excategoryData[sRow , sCol] = tsnResult.AOIMapCategory[sRow-2,sCol-2].ToString();
                                    }
                                
                                }
                            }
                        }
                        else if (tsnResult.product_id == "ASAW0741A_1")
                        {
                            for (int sRow = 5; sRow <= 203; sRow++)
                            {
                                for (int sCol = 6; sCol <= 180; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow, sCol-2] =
                                            tsnResult.AOIMapData[sRow - 5, sCol - 6];
                                        deviceMapResult.categoryData[sRow, sCol-2] =
                                            tsnResult.AOIMapCategory[sRow - 5, sCol - 6];
                                        // 2,81
                                        // deviceMapResult.testResult[7, 85] = 2;
                                        // deviceMapResult.categoryData[7 , 85] = 59;
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol-2] =
                                                tsnResult.AOIMapCategory[sRow - 5, sCol - 6].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if (tsnResult.product_id == "ASAW0366A_1")
                        {
                            for (int sRow = 5; sRow <= 201; sRow++)
                            {
                                for (int sCol = 7; sCol <= 192; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow+1, sCol-3] =
                                            tsnResult.AOIMapData[sRow - 5, sCol - 7];
                                        deviceMapResult.categoryData[sRow+1, sCol-3] =
                                            tsnResult.AOIMapCategory[sRow - 5, sCol - 7];
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow+1, sCol-3] =
                                                tsnResult.AOIMapCategory[sRow - 5, sCol - 7].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if (tsnResult.product_id == "ASAW0741B_1")
                        {
                            for (int sRow = 5; sRow <= 210; sRow++)
                            {
                                for (int sCol = 6; sCol <= 179; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow, sCol-2] =
                                            tsnResult.AOIMapData[sRow - 5, sCol - 6];
                                        deviceMapResult.categoryData[sRow, sCol-2] =
                                            tsnResult.AOIMapCategory[sRow - 5, sCol - 6];
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol-2] =
                                                tsnResult.AOIMapCategory[sRow - 5, sCol - 6].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if (tsnResult.product_id == "ASAW3940A_1" || tsnResult.product_id == "ASAW3940B_1")
                        {
                            for (int sRow = 6; sRow <= 176; sRow++)
                            {
                                for (int sCol = 6; sCol <= 179; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow, sCol] = tsnResult.AOIMapData[sRow - 4, sCol - 4];
                                        // deviceMapResult.testResult[6,81] = 2;
                                        // deviceMapResult.categoryData[6,81] = 59;
                                        deviceMapResult.categoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 4, sCol - 4];
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 4, sCol - 4].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if (tsnResult.product_id == "ASAW0826E_1")
                        {
                            for (int sRow = 4; sRow <= 137; sRow++)
                            {
                                for (int sCol = 6; sCol <= 219; sCol++)
                                {

                                    try
                                    {
                                        //  100 1
                                        // deviceMapResult.testResult[4,107] = 2;
                                        // deviceMapResult.categoryData[4,107] = 59;

                                        deviceMapResult.testResult[sRow, sCol] =
                                            tsnResult.AOIMapData[sRow - 2, sCol - 6];
                                        deviceMapResult.categoryData[sRow, sCol] =
                                            tsnResult.AOIMapCategory[sRow - 2, sCol - 6];
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] =
                                                tsnResult.AOIMapCategory[sRow - 2, sCol - 6].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }


                                }
                            }
                        }
                        else if (tsnResult.product_id == "ASAW4041A_1")
                        {
                            for (int sRow = 5; sRow <= 184; sRow++)
                            {
                                for (int sCol = 5; sCol <= 179; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow, sCol] =
                                            tsnResult.AOIMapData[sRow - 4, sCol - 4];
                                        deviceMapResult.categoryData[sRow, sCol] =
                                            tsnResult.AOIMapCategory[sRow - 4, sCol - 4];
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] =
                                                tsnResult.AOIMapCategory[sRow - 4, sCol - 4].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }


                                }
                            }
                        }
                        else if (tsnResult.product_id == "H1752")
                        {
                            for (int sRow = 2; sRow <= 221; sRow++)
                            {
                                for (int sCol = 2; sCol <= 276; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow, sCol] =
                                            tsnResult.AOIMapData[sRow - 1, sCol - 1];
                                        deviceMapResult.categoryData[sRow, sCol] =
                                            tsnResult.AOIMapCategory[sRow - 1, sCol - 1];
                                        // 2,122
                                        // deviceMapResult.testResult[2, 122] = 2;
                                        //     deviceMapResult.categoryData[2, 122] = 59;

                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] =
                                                tsnResult.AOIMapCategory[sRow - 1 , sCol - 1].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.StackTrace);
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if (tsnResult.product_id == "YSZ316BR0002")
                        {
                            for (int sRow = 4; sRow <= 446; sRow++)
                            {
                                for (int sCol = 2; sCol <= 347; sCol++)
                                {

                                    try
                                    {
                                        //5 153 1 151 
                                        // deviceMapResult.testResult[5, 153] = 2;
                                        // deviceMapResult.categoryData[5, 153] = 59;

                                        deviceMapResult.testResult[sRow, sCol] = tsnResult.AOIMapData[sRow - 4, sCol - 2];
                                        deviceMapResult.categoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 4, sCol - 2];
                                        
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 4 , sCol - 2].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"sow---{sRow}---scol---{sCol}");
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if (tsnResult.product_id == "YSZ316BR0006" || productId == "YSZ316BR0006-F1")
                        {
                            for (int sRow = 4; sRow <= 352; sRow++)
                            {
                                for (int sCol = 1; sCol <= 458; sCol++)
                                {

                                    try
                                    {
                                        //4 211   1 222 
                                        // deviceMapResult.testResult[4, 211] = 2;
                                        // deviceMapResult.categoryData[4, 211] = 59;

                                        deviceMapResult.testResult[sRow, sCol] = tsnResult.AOIMapData[sRow - 3, sCol + 11];
                                        deviceMapResult.categoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 3, sCol + 11];
                                        
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 3 , sCol + 11].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"sow---{sRow}---scol---{sCol}");
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if (tsnResult.product_id == "Y0TS10BR0012" || tsnResult.product_id == "Y0TS10BR0015")
                        {
                            for (int sRow = 1; sRow <= 35; sRow++)
                            {
                                for (int sCol = 1; sCol <= 45; sCol++)
                                {

                                    try
                                    {

                                        // deviceMapResult.testResult[1, 17] = 2;
                                        // deviceMapResult.categoryData[1, 17] = 99;
                                        deviceMapResult.testResult[sRow, sCol] = tsnResult.AOIMapData[sRow, sCol];
                                        deviceMapResult.categoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow , sCol];
                                        
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow , sCol].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"sow---{sRow}---scol---{sCol}");
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if (tsnResult.product_id == "ASAW3439D_1" || tsnResult.product_id == "ASAW3439D_2" || tsnResult.product_id == "ASAW3439D_1_OPC")
                        {
                            for (int sRow = 6; sRow <= 208; sRow++)
                            {
                                for (int sCol = 6; sCol <= 213; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow, sCol] = tsnResult.AOIMapData[sRow - 5, sCol - 5];
                                        deviceMapResult.categoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 5, sCol - 5];
                                        
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 5 , sCol - 5].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"sow---{sRow}---scol---{sCol}");
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if ( productId == "ASAW036625E_1")
                        {
                            for (int sRow = 5; sRow <= 147; sRow++)
                            {
                                for (int sCol = 5 ; sCol <= 180; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow, sCol] = tsnResult.AOIMapData[sRow - 4, sCol - 4];
                                        deviceMapResult.categoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 4, sCol - 4];
                                        
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 4 , sCol - 4].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"sow---{sRow}---scol---{sCol}");
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if ( productId == "ASAW404107C_1")
                        {
                            for (int sRow = 5; sRow <= 146; sRow++)
                            {
                                for (int sCol = 4 ; sCol <= 179; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow, sCol] = tsnResult.AOIMapData[sRow - 3, sCol - 4];
                                        deviceMapResult.categoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 3, sCol - 4];
                                        
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 3 , sCol - 4].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"sow---{sRow}---scol---{sCol}");
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if (tsnResult.product_id == "YSH589BR0001")
                        {
                            for (int sRow = 1; sRow <= 93; sRow++)
                            {
                                for (int sCol = 1; sCol <= 103; sCol++)
                                {

                                    try
                                    {

                                        // deviceMapResult.testResult[1, 47] = 2;
                                        // deviceMapResult.categoryData[1, 47] = 59;

                                        deviceMapResult.testResult[sRow, sCol] = tsnResult.AOIMapData[sRow-1, sCol];
                                        deviceMapResult.categoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow-1 , sCol];
                                        
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow-1 , sCol].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"sow---{sRow}---scol---{sCol}");
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if ( productId == "ZSZ3160009" )
                        {
                            for (int sRow = 5; sRow <= 147; sRow++)
                            {
                                for (int sCol = 5 ; sCol <= 180; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow, sCol] = tsnResult.AOIMapData[sRow - 5, sCol - 5];
                                        deviceMapResult.categoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 5, sCol - 5];
                                        
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 5 , sCol - 5].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"sow---{sRow}---scol---{sCol}");
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if ( productId == "ZSZ3160008" )
                        {
                            for (int sRow = 4; sRow <= 146; sRow++)
                            {
                                for (int sCol = 5 ; sCol <= 179; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow, sCol] = tsnResult.AOIMapData[sRow - 4, sCol - 5];
                                        deviceMapResult.categoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 4, sCol - 5];
                                        
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 4 , sCol - 5].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"sow---{sRow}---scol---{sCol}");
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if ( productId == "FX266RB5103W" )
                        {
                            for (int sRow = 3; sRow <= 119; sRow++)
                            {
                                for (int sCol = 5 ; sCol <= 178; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow, sCol] = tsnResult.AOIMapData[sRow - 2, sCol - 4];
                                        deviceMapResult.categoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 2, sCol - 4];
                                        
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] = tsnResult.AOIMapCategory[sRow - 2 , sCol - 4].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"sow---{sRow}---scol---{sCol}");
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                
                                }
                            }
                        }
                        else if (tsnResult.product_id == "WSAW036625A_1")
                        {
                            for (int sRow = 3; sRow <= 119; sRow++)
                            {
                                for (int sCol = 5; sCol <= 178; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow, sCol] =
                                            tsnResult.AOIMapData[sRow - 2, sCol - 4];
                                        deviceMapResult.categoryData[sRow, sCol] =
                                            tsnResult.AOIMapCategory[sRow - 2, sCol - 4];
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] =
                                                tsnResult.AOIMapCategory[sRow - 2, sCol - 4].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }


                                }
                            }
                        }
                        else if (tsnResult.product_id == "ASAW0826F_1")
                        {
                            for (int sRow = 3; sRow <= 137; sRow++)
                            {
                                for (int sCol = 6; sCol <= 219; sCol++)
                                {

                                    try
                                    {
                                        deviceMapResult.testResult[sRow, sCol] =
                                            tsnResult.AOIMapData[sRow - 2, sCol - 5];
                                        deviceMapResult.categoryData[sRow, sCol] =
                                            tsnResult.AOIMapCategory[sRow - 2, sCol - 5];
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow, sCol] =
                                                tsnResult.AOIMapCategory[sRow - 2, sCol - 5].ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }


                                }
                            }
                        }
                        else
                        {
                             // 写入AOI数据到测试结果数据
                            for (int sRow = deviceMapResult.startRow-1; sRow <= deviceMapResult.endRow; sRow++)
                            {
                                for (int sCol = deviceMapResult.startCol-1; sCol <= deviceMapResult.endCol; sCol++)
                                {
                            
                                    if (tsnResult.product_id.Contains("N41881C") || tsnResult.product_id == "N46307B" || tsnResult.product_id == "YSZ316BR0003" || tsnResult.product_id == "U06A-AB1-1" 
                                        || tsnResult.product_id == "GM1V1" || tsnResult.product_id == "GM1VJ" || tsnResult.product_id == "G0RT6" || tsnResult.product_id == "G0RL3" || tsnResult.product_id == "GM1WE" || tsnResult.product_id == "GM1V0" )
                                    { 
                                        deviceMapResult.testResult[sRow-1 , sCol-1 ] = tsnResult.AOIMapData[sRow - deviceMapResult.startRow + 1, sCol - deviceMapResult.startCol + 1];
                                        deviceMapResult.categoryData[sRow-1  , sCol-1] = tsnResult.AOIMapCategory[sRow - deviceMapResult.startRow + 1, sCol - deviceMapResult.startCol + 1];
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow-1 , sCol-1] = tsnResult.AOIMapCategory[sRow - deviceMapResult.startRow + 1, sCol - deviceMapResult.startCol + 1].ToString();
                                        }
                                    }
                                    else
                                    {
                                        deviceMapResult.testResult[sRow, sCol] = tsnResult.AOIMapData[sRow - deviceMapResult.startRow + 1, sCol - deviceMapResult.startCol + 1];
                                        deviceMapResult.categoryData[sRow  , sCol] = tsnResult.AOIMapCategory[sRow - deviceMapResult.startRow + 1, sCol - deviceMapResult.startCol + 1];
                                        if (deviceMapResult.isExtRes == "1")
                                        {
                                            deviceMapResult.excategoryData[sRow , sCol] = tsnResult.AOIMapCategory[sRow - deviceMapResult.startRow + 1, sCol - deviceMapResult.startCol + 1].ToString();
                                        }
                                    }
                                }
                            }
                        }
                        

                        #region 测试导图文件

                        // using (StreamWriter writer = new StreamWriter("D:\\RiderProjects\\aoitest\\AOITest\\vega\\aoitxt.txt"))
                        // {
                        //     for (int x = 0; x < tsnResult.AOIMapData.GetLength(0); x++)
                        //     {
                        //         for (int y = 0; y < tsnResult.AOIMapData.GetLength(1); y++)
                        //         {
                        //             writer.Write(tsnResult.AOIMapData[x,y]);
                        //         }
                        //         await writer.WriteLineAsync("");
                        //     }
                        //     
                        // }
                        //
                        //
                        // using (StreamWriter writer = new StreamWriter("D:\\RiderProjects\\aoitest\\AOITest\\vega\\aoitxt1.txt"))
                        // {
                        //     for (int x = 0; x < tsnResult.AOIMapCategory.GetLength(0); x++)
                        //     {
                        //         for (int y = 0; y < tsnResult.AOIMapCategory.GetLength(1); y++)
                        //         {
                        //             writer.Write(tsnResult.AOIMapCategory[x, y]);
                        //         }
                        //         await writer.WriteLineAsync("");
                        //     }
                        //     
                        // }


                        #endregion
                        


                        #region 测试

                         // string aoitxt = "D:\\RiderProjects\\aoitest\\AOITest\\vega\\aoitxt.txt";
                        //
                        // using (StreamWriter writer = new StreamWriter(aoitxt))
                        // {
                        //     writer.WriteLine("Version: "+deviceMapResult.version);
                        //     
                        //     writer.WriteLine("linesize: "+deviceMapResult.linesize);
                        //     writer.WriteLine("linesize: "+deviceMapResult.rowsize);
                        //     writer.WriteLine("DeviceName: "+deviceMapResult.DeviceName);
                        //     writer.WriteLine("newnumflat: "+deviceMapResult.newnumflat);
                        //     
                        //     
                        //     // 遍历数组的行
                        //     for (int x = 0; x < deviceMapResult.testResult.GetLength(0); x++)
                        //     {
                        //         // 遍历数组的列
                        //         for (int y = 0; y < deviceMapResult.testResult.GetLength(1); y++)
                        //         {
                        //             // 将数组元素写入文件，后跟一个制表符（或空格）以分隔列
                        //             writer.Write(deviceMapResult.testResult[x, y] + " ");
                        //         }
                        //         // 在每一行结束后写入一个换行符
                        //         writer.WriteLine();
                        //     }
                        // }
                        //
                        //
                        //
                        // string aoitxt2 = "D:\\RiderProjects\\aoitest\\AOITest\\vega\\aoitxt2.txt";
                        //
                        // using (StreamWriter writer = new StreamWriter(aoitxt2))
                        // {
                        //     // 遍历数组的行
                        //     for (int x = 0; x < deviceMapResult.categoryData.GetLength(0); x++)
                        //     {
                        //         // 遍历数组的列
                        //         for (int y = 0; y < deviceMapResult.categoryData.GetLength(1); y++)
                        //         {
                        //             // 将数组元素写入文件，后跟一个制表符（或空格）以分隔列
                        //             writer.Write(deviceMapResult.categoryData[x, y] + " ");
                        //         }
                        //         // 在每一行结束后写入一个换行符
                        //         writer.WriteLine();
                        //     }
                        // }
                        //
                        //
                        // string aoitxt3 = "D:\\RiderProjects\\aoitest\\AOITest\\vega\\aoitxt3.txt";
                        //
                        // using (StreamWriter writer = new StreamWriter(aoitxt3))
                        // {
                        //     // 遍历数组的行
                        //     for (int x = 0; x < deviceMapResult.excategoryData.GetLength(0); x++)
                        //     {
                        //         // 遍历数组的列
                        //         for (int y = 0; y < deviceMapResult.excategoryData.GetLength(1); y++)
                        //         {
                        //             // 将数组元素写入文件，后跟一个制表符（或空格）以分隔列
                        //             writer.Write(deviceMapResult.excategoryData[x, y] + " ");
                        //         }
                        //         // 在每一行结束后写入一个换行符
                        //         writer.WriteLine();
                        //     }
                        // }
                        
                        
                        // Console.WriteLine("数组已写入到文件: " + aoitxt2);

                        #endregion
                   
                    

                    
                        FileStream fileStream = new FileStream(templateDatPath, FileMode.Open, FileAccess.ReadWrite);
                        byte[] aryContent = new byte[fileStream.Length];
                        fileStream.Read(aryContent, 0, aryContent.Length);
                        fileStream.Close();

                        #region 解析total信息

                        // Wafer ID
                        string tmpWaferid = tsnResult.wafer_id.PadRight(21);
                        for (int I = 60; I <= 80; I++)
                        {
                            aryContent[I] = (byte)tmpWaferid[I - 60];
                           
                        }
                        
                        // Lot No.
                        string tmpLotNo = lotNo.PadRight(18, ' ');
                        for (int I = 82; I <= 99; I++)
                        {
                            aryContent[I] = (byte)tmpLotNo[I - 82];
                        }
                        
                        // Slot No.
                        string tmpslotNo = slotNo.ToString("X").PadLeft(4, '0');
                        
                        
                        for (int I = 102; I <= 103; I++)
                        {
                            string value = tmpslotNo.Substring((I - 102) * 2, 2);
                            aryContent[I] = Convert.ToByte(value, 16);
                        }
                        
                        // Tot Test Die
                        string tmpTestDie = tsnResult.totTestDie.ToString("X4");
                        aryContent[210] = Convert.ToByte(tmpTestDie.Substring(0, 2), 16);
                        
                        // Tot Pass Die
                        string tmppassDie = tsnResult.totPassDie.ToString("X4");
                        aryContent[212] = Convert.ToByte(tmppassDie.Substring(0, 2), 16);
                        aryContent[213] = Convert.ToByte(tmppassDie.Substring(2, 2), 16);
                        
                        // Tot Fail Die
                        string tmpfailDie = tsnResult.totFailDie.ToString("X4");
                        aryContent[214] = Convert.ToByte(tmpfailDie.Substring(0, 2), 16);
                        aryContent[215] = Convert.ToByte(tmpfailDie.Substring(2, 2), 16);

                        #endregion
                        
                        
                        // Test Result
                        int F = 236;
                        for (int sRow = 1; sRow <= deviceMapResult.linesize; sRow++)
                        {
                            for (int sCol = 1; sCol <= deviceMapResult.rowsize; sCol++)
                            {
                                for (int j = 1; j <= deviceMapResult.dataForm; j += 2)
                                {
                                    long tmpRes;
                                    string tmp1Res = string.Empty;
                                    for (int posRes = F; posRes <= F + 1; posRes++)
                                    {
                                        tmp1Res += StringUtils.Dec2Hex(aryContent[posRes]);
                                    }
                                    tmpRes = Convert.ToInt64(tmp1Res, 16);
                                    string tRes = Convert.ToString(tmpRes, 2).PadLeft(16, '0');
                                    switch (j)
                                    {
                                        case 1:
                                            int tmp1StData = Convert.ToInt32(tRes.Substring(0, 8), 2);
                                            
                                            string binStr = Convert.ToString(deviceMapResult.testResult[sRow-1, sCol-1],2).PadLeft(2, '0') + "000000";
                                            
                                            int newResult = Convert.ToInt32(binStr, 2);
                                            aryContent[F] = (byte)(tmp1StData & 63 | newResult);
                                            break;
                                        case 5:
                                            int tmpCategory = Convert.ToInt32(tRes.Substring(10, 6), 2);
                                            byte tmpCode = aryContent[F + 1];
                                            int newcode = deviceMapResult.categoryData[sRow - 1, sCol - 1] - tmpCategory + tmpCode;
                                            aryContent[F + 1] = (byte)newcode;
                                            break;
                                    }
                                    F += 2;
                                }
                            }
                        }
                        
                    
                    
                        if (deviceMapResult.isExtHead == 1)
                        {
                            F += 52;
        
                            // total tested dice
                            string tmpTestDie2 = tsnResult.totTestDie.ToString("X").PadLeft(8, '0');
                            for (int posExtHead = F; posExtHead <= F + 3; posExtHead++)
                            {
                                aryContent[posExtHead] = Convert.ToByte(tmpTestDie2.Substring((posExtHead - F) * 2, 2), 16);
                            }
                            F += 4;
        
                            // total pass dice
                            string tmppassDie2 = tsnResult.totPassDie.ToString("X").PadLeft(8, '0');
                            for (int posExtHead = F; posExtHead <= F + 3; posExtHead++)
                            {
                                aryContent[posExtHead] = Convert.ToByte(tmppassDie2.Substring((posExtHead - F) * 2, 2), 16);
                            }
                            F += 4;
        
                            // total fail dice
                            string tmpfailDie2 = tsnResult.totFailDie.ToString("X").PadLeft(8, '0');
                            for (int posExtHead = F; posExtHead <= F + 3; posExtHead++)
                            {
                                aryContent[posExtHead] = Convert.ToByte(tmpfailDie2.Substring((posExtHead - F) * 2, 2), 16);
                            }
                            F += 4;

                            string tmpfailDie3 = tsnResult.totFailDie.ToString("X").PadLeft(8, '0');
                            for (int posExtHead = F; posExtHead <= F + 3; posExtHead++)
                            {
                                aryContent[posExtHead] = Convert.ToByte(tmpfailDie3.Substring((posExtHead - F) * 2, 2), 16);
                            }
                            F += 4;
                            
                            
                            F += 104;
                        }

                        if (deviceMapResult.isExtRes == "1")
                        {
                            for (int sRow = 1; sRow <= deviceMapResult.linesize; sRow++)
                            {
                                for (int sCol = 1; sCol <= deviceMapResult.rowsize; sCol++)
                                {
                                    for (int j = 1; j <= 4; j += 2)
                                    {
                                        long tmpexRes;
                                        string tmp1ExRes = "";
                                        for (int posexRes = F; posexRes <= F + 1; posexRes++)
                                        {
                                            tmp1ExRes += StringUtils.Dec2Hex(aryContent[posexRes]);
                                        }
                                        tmpexRes = Convert.ToInt64(tmp1ExRes,16);
                                        string texRes = StringUtils.DEC_to_BIN(tmpexRes).PadLeft(16, '0');
                                        switch (j)
                                        {
                                            case 1:
                                                if (deviceMapResult.version == 2 || deviceMapResult.version == 3)
                                                {
                                                    aryContent[F + 1] = Convert.ToByte(deviceMapResult.excategoryData[sRow - 1, sCol - 1]);
                                                }
                                                break;
                                            case 3:
                                                if (deviceMapResult.version == 4 || deviceMapResult.version == 5)
                                                {
                                                    long newcode = long.Parse(deviceMapResult.excategoryData[sRow - 1, sCol - 1]); 
                                                    string tmpWord = texRes.Substring(0, 6) + StringUtils.DEC_to_BIN(newcode).PadLeft(10,'0');
                                                    aryContent[F] = (byte)StringUtils.BinToDec((tmpWord.Substring(0, 8)));
                                                    aryContent[F + 1] = (byte)StringUtils.BinToDec(tmpWord.Substring(8, 8));
                                                }
                                                if (deviceMapResult.version == 7)
                                                {
                                                    long newcode = long.Parse(deviceMapResult.excategoryData[sRow - 1, sCol - 1]); 
                                                    string tmpWord = texRes.Substring(0, 2) + StringUtils.DEC_to_BIN(newcode).PadLeft(14,'0');
                                                    aryContent[F] = (byte)StringUtils.BinToDec((tmpWord.Substring(0, 8)));
                                                    aryContent[F + 1] = (byte)StringUtils.BinToDec(tmpWord.Substring(8, 8));
                                                }
                                                break;
                                        }
                                        F += 2;
                                    }
                                }
                            }
                        }



                        if (File.Exists(outputFile))
                        {
                            string nameDpat = Path.GetFileNameWithoutExtension(files[i]);
                            if (nameDpat.Contains("DPAT"))
                            {
                                using (BinaryWriter bw = new BinaryWriter(File.Open(outputFile, FileMode.Create)))
                                {
                                    bw.Write(aryContent, 0, aryContent.Length);
                                }
                            
                                // 已经导完图，删掉
                                File.Delete(files[i]);
                            }
                            else
                            {
                                StringUtils.CheckFile(outputFile);
                            }
                            
                        }
                        else
                        {
                            using (BinaryWriter bw = new BinaryWriter(File.Open(outputFile, FileMode.Create)))
                            {
                                bw.Write(aryContent, 0, aryContent.Length);
                            }
                            
                            // 已经导完图，删掉
                            File.Delete(files[i]);
                            Console.WriteLine(@$"{filename}该片导图测试完成");
                        }
                        
                    }
                    
                }
                catch (UnauthorizedAccessException ex)
                {
                    Console.WriteLine($"Access denied.: {ex.Message}");
                    Console.WriteLine($"Access denied.: {ex.StackTrace}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"错误信息: {ex.Message}");
                    Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                }
                
            }
            
            
            
            

        }


        /// <summary>
        /// 获取aoi文件的信息
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private static async Task<(string waferId, string productId,string lotNo, int slotNo)> GetLotInfo(string filePath)
        {
            
            string waferId = string.Empty;
            string productId = string.Empty;
            string lotNo = string.Empty;
            int slotNo = 0;

            // 是否需要excel N46307B  N41881C
            bool isExcel = false;
            
            using (StreamReader reader = new StreamReader(filePath))
            {
                string? line;
                
                while ((line = await reader.ReadLineAsync()) != null)
                {

                    if (line.StartsWith("RowData:"))
                    {
                        break;
                    }

                    if (line.StartsWith("[SOFT BIN MAP]"))
                    {
                        break;
                    }

                    if (line.Contains(":"))
                    {
                        string[] parts = line.Split(':');
                        line = parts[0].Trim() + ":" + parts[1].Trim();
                    }
                   
                   
                    Regex productRegex = new Regex(@"DEVICE:(\S+)",RegexOptions.IgnoreCase);
                    Regex lotRegex = new Regex(@"LOT:(\S+)",RegexOptions.IgnoreCase);
                    Regex waferRegex = new Regex(@"Wafer:(\S+)",RegexOptions.IgnoreCase);
                    
                    
                    Regex lotSzwRegex = new Regex(@"Cust Lot No:(\S+)",RegexOptions.IgnoreCase);
                    Regex waferSzwRegex = new Regex(@"Wafer Num:(\S+)",RegexOptions.IgnoreCase);
                    
                    
                    
                    Regex productRegex2 = new Regex(@"PRODUCT_ID=(\S+)",RegexOptions.IgnoreCase);
                    Regex lotRegex2 = new Regex(@"Lot_ID=(\S+)",RegexOptions.IgnoreCase);
                    Regex waferRegex2 = new Regex(@"WAFER_ID=(\S+)",RegexOptions.IgnoreCase);
                    
                    
                    Regex productRegex3 = new Regex(@"Product No\s+(\S+)",RegexOptions.IgnoreCase);
                    Regex lotRegex3 = new Regex(@"Lot ID\s+(\S+)",RegexOptions.IgnoreCase);
                    Regex waferRegex3 = new Regex(@"Wafer ID\s+(\S+)",RegexOptions.IgnoreCase);
                    
                    
                    
                    Regex productRegex4 = new Regex(@"PRODUCT ID:(\S+)",RegexOptions.IgnoreCase);
                    Regex lotRegex4 = new Regex(@"LOT ID:(\S+)",RegexOptions.IgnoreCase);
                    Regex waferRegex4 = new Regex(@"WAFER ID:(\S+)",RegexOptions.IgnoreCase);

                    
                    Match productMatch = productRegex.Match(line);
                    Match productMatch2 = productRegex2.Match(line);
                    Match productMatch3 = productRegex3.Match(line);
                    Match productMatch4 = productRegex4.Match(line);
                    
                    if (productMatch.Success)
                    {
                        productId = productMatch.Groups[1].Value;
                        if (productId == "N41881C" || productId == "N46307B")
                        {
                            isExcel = true;
                        }
                    }

                    if (productMatch2.Success)
                    {
                        productId = productMatch2.Groups[1].Value;
                    }
                    
                    if (productMatch3.Success)
                    {
                        productId = productMatch3.Groups[1].Value;
                    }

                    if (productMatch4.Success)
                    {
                        productId = productMatch4.Groups[1].Value;
                    } 
                    
                    Match lotMatch = lotRegex.Match(line);
                    Match lotSzwMatch = lotSzwRegex.Match(line);
                    Match lotMatch2 = lotRegex2.Match(line);
                    Match lotMatch3 = lotRegex3.Match(line);
                    Match lotMatch4 = lotRegex4.Match(line);
                    if (lotMatch.Success)
                    {
                        lotNo = lotMatch.Groups[1].Value;
                    }

                    if (lotSzwMatch.Success)
                    {
                        lotNo = lotSzwMatch.Groups[1].Value;
                    }

                    if (lotMatch2.Success)
                    {
                        lotNo = lotMatch2.Groups[1].Value;
                    }
                    
                    if (lotMatch3.Success)
                    {
                        lotNo = lotMatch3.Groups[1].Value;
                    }

                    if (lotMatch4.Success)
                    {
                        lotNo = lotMatch4.Groups[1].Value;
                    }
                    
                    Match waferMatch = waferRegex.Match(line);
                    if (waferMatch.Success)
                    {
                        string waferIdStr = waferMatch.Groups[1].Value;
                        waferId = waferIdStr;
                        // Match waferIdNumMatch = Regex.Match(waferIdStr, @"(\d{2})");
                        bool isInt = int.TryParse(waferId, out int isIntResult);
                        if (isInt)
                        {
                            slotNo = isIntResult;
                        }
                        else 
                        {
                            string n4188CJson = await File.ReadAllTextAsync(N4188CPath);

                            var waferList = JsonConvert.DeserializeObject<List<ExcelJson>>(n4188CJson);

                            if (waferList != null)
                            {
                                var result = waferList.FirstOrDefault(w => w.刻号 == waferIdStr);

                                if (result == null && isExcel)
                                {
                                    List<string> mailReceiver = StringUtils.GetMailReceiver();   
                                    string subject = "没有对应的excel文件";
                                    Console.WriteLine("缺少excel文件或者excel文件格式不对，没有找到对应的 WAFER_ID");
                                    MailHelper.SendMail(subject,"缺少excel文件或者excel文件格式不对，没有找到对应的 WAFER_ID",mailReceiver);
                                }
        
                                if (result != null)
                                {
                                    slotNo = result.WAFER_ID;
                                    Console.WriteLine($"找到的 WAFER_ID: {result.WAFER_ID}");
                                }
                            }
                        }
                    }
                    
                    Match waferSzwMatch = waferSzwRegex.Match(line);
                    Match waferMatch2 = waferRegex2.Match(line);
                    Match waferMatch3 = waferRegex3.Match(line);
                    Match waferMatch4 = waferRegex4.Match(line);
                    if (waferSzwMatch.Success)
                    {
                        waferId = waferSzwMatch.Groups[1].Value;
                        slotNo = int.Parse(waferSzwMatch.Groups[1].Value);
                    }

                    if (waferMatch2.Success)
                    {
                        waferId = waferMatch2.Groups[1].Value;
                        slotNo = int.Parse(waferMatch2.Groups[1].Value);
                    }
                    
                    if (waferMatch3.Success)
                    {
                        waferId = waferMatch3.Groups[1].Value;
                        slotNo = int.Parse(waferMatch3.Groups[1].Value);
                    }
                    
                    if (waferMatch4.Success)
                    {
                        waferId = waferMatch4.Groups[1].Value;
                        slotNo = int.Parse(waferMatch4.Groups[1].Value);
                    }
                    
                    
                }
                
                // waferId = $"{lotNo}-{slotNo:000}";
                
            }


            
            return (waferId,productId,lotNo,slotNo);


        }



        private static ReadDeviceMapResult  ReadDeviceMap(string templateDatPath)
        {
            if (!File.Exists(templateDatPath))
            {
                throw new FileNotFoundException("templateDatPath  doesn't exist!");
            }

            
            ReadDeviceMapResult deviceMapResult = new ReadDeviceMapResult();
            
            
            using (FileStream fileStream = new FileStream(templateDatPath, FileMode.Open, FileAccess.Read))
            {
                // 获取文件长度
                long fileLength = fileStream.Length;
                byte[] aryContent = new byte[fileLength];
        
                // 读取文件内容到字节数组
                fileStream.Read(aryContent, 0, (int)fileLength);
        
                // 关闭文件流
                fileStream.Close();

                #region 处理dat详细信息
                
                deviceMapResult.DeviceName = String.Empty;
                
                
                // 处理设备名称
                StringBuilder deviceName = new StringBuilder();
                for (int i = 20; i <= 35; i++)
                {
                    if (aryContent[i] == 0)
                    {
                        deviceName.Append("");
                    }
                    else
                    {
                        deviceName.Append((char)aryContent[i]);
                    }
                }
                deviceMapResult.DeviceName = deviceName.ToString().Trim();
                
                string tmpflat = string.Empty;
                for (int i = 48; i <= 49; i++)
                {
                    tmpflat += StringUtils.Dec2Hex(aryContent[i]);
                }
                deviceMapResult.newnumflat = Convert.ToInt64(tmpflat, 16);

                // map version
                deviceMapResult.version = aryContent[51];
                
                Console.WriteLine($"map version: {deviceMapResult.version}");

                // row size
                string tmpRow = string.Empty;
                for (int i = 52; i <= 53; i++)
                {
                    tmpRow += StringUtils.Dec2Hex(aryContent[i]);
                }
                deviceMapResult.rowsize = Convert.ToInt32(tmpRow, 16);

                // line size
                string tmpLineSize = string.Empty;
                for (int i = 54; i <= 55; i++)
                {
                    tmpLineSize += StringUtils.Dec2Hex(aryContent[i]);
                }
                deviceMapResult.linesize = Convert.ToInt32(tmpLineSize, 16);

                // map data form
                string tmpDataform = string.Empty;
                for (int i = 56; i <= 59; i++)
                {
                    tmpDataform += StringUtils.Dec2Hex(aryContent[i]);
                }
                deviceMapResult.mapdataform = Convert.ToInt64(tmpDataform, 16);
                deviceMapResult.dataForm = (deviceMapResult.mapdataform == 0) ? 6 : (int)deviceMapResult.mapdataform;

                // Number of line category
                string tmpCate = string.Empty;
                for (int i = 220; i <= 223; i++)
                {
                    tmpCate += StringUtils.Dec2Hex(aryContent[i]);
                }
                deviceMapResult.numOfCate = Convert.ToInt32(tmpCate, 16);
                
                
                
                string tmpConfig = string.Empty;
                for (int i = 228; i <= 229; i++)
                {
                    tmpConfig += StringUtils.Dec2Hex(aryContent[i]);
                }
                deviceMapResult.mapconfig = Convert.ToInt64(tmpConfig, 16);
                string config = Convert.ToString(deviceMapResult.mapconfig, 2).PadLeft(16, '0');

                // string isLineCat = config.Substring(13, 1); 
                deviceMapResult.isExtHead = int.Parse(config.Substring(12, 1));
                deviceMapResult.isExtRes = config.Substring(11, 1);
                // string isExtLineCat = config.Substring(10, 1);

                
                // deviceMapResult.testResult = new int[500,500];
                // deviceMapResult.categoryData = new int[500,500];
                // deviceMapResult.testSite = new int[500,500];
                // deviceMapResult.excategoryData = new string[500,500];
                deviceMapResult.testResult = new int[deviceMapResult.linesize + 1,deviceMapResult.rowsize + 1];
                deviceMapResult.categoryData = new int[deviceMapResult.linesize + 1,deviceMapResult.rowsize + 1];
                deviceMapResult.testSite = new int[deviceMapResult.linesize + 1,deviceMapResult.rowsize + 1];
                deviceMapResult.excategoryData = new string[deviceMapResult.linesize + 1,deviceMapResult.rowsize + 1];
                
                
                deviceMapResult.startRow = 0;
                deviceMapResult.endRow = 0;
                deviceMapResult.startCol = 0;
                deviceMapResult.endCol = 0;
                int I = 236;

                for (int sRow = 1; sRow <= deviceMapResult.linesize; sRow++)
                {
                    string tmpLine = string.Empty;
                    for (int sCol = 1; sCol <= deviceMapResult.rowsize; sCol++)
                    {
                        for (int j = 1; j <= deviceMapResult.dataForm; j += 2)
                        {
                            long tmpRes;
                            string tmp1Res = string.Empty;
                            for (int posRes = I; posRes <= I + 1; posRes++)
                            {
                                tmp1Res += StringUtils.Dec2Hex(aryContent[posRes]);
                            }
                            tmpRes = Convert.ToInt64(tmp1Res, 16);
                            string tRes = Convert.ToString(tmpRes, 2).PadLeft(16, '0');

                            switch (j)
                            {
                                case 1:
                                    try
                                    {
                                        deviceMapResult.testResult[sRow,sCol] = StringUtils.BinToDec(tRes.Substring(0, 2));
                                        tmpLine += (deviceMapResult.testResult[sRow,sCol] == 0) ? "0" : "1";
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($"INDEX===={sRow}====={sCol}");
                                        Console.WriteLine(ex.Message);
                                    }
                                   
                                    break;
                                case 5:
                                    
                                    try
                                    {
                                        deviceMapResult.testSite[sRow,sCol] = StringUtils.BinToDec(tRes.Substring(2, 6));
                                        deviceMapResult.categoryData[sRow,sCol] = StringUtils.BinToDec(tRes.Substring(10, 6));
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }
                                    
                                    break;
                            }
                            I += 2;
                        }
                    }
                    
                    int indexFirstOne = tmpLine.IndexOf('1');
                    int indexLastOne = tmpLine.LastIndexOf('1');
                    
                    if (indexFirstOne > -1)
                    {
                        if (deviceMapResult.startRow == 0 || sRow < deviceMapResult.startRow)
                        {
                            deviceMapResult.startRow = sRow;
                        }
                        if (deviceMapResult.endRow == 0 || sRow > deviceMapResult.endRow)
                        {
                            deviceMapResult.endRow = sRow;
                        }
                        if (deviceMapResult.startCol == 0 || indexFirstOne + 1 < deviceMapResult.startCol)
                        {
                            deviceMapResult.startCol = indexFirstOne + 1;
                        }
                        if (deviceMapResult.endCol == 0 || indexLastOne + 1 > deviceMapResult.endCol)
                        {
                            deviceMapResult.endCol = indexLastOne + 1;
                        }
                    }
                }
                
    
                
                
                if (deviceMapResult.isExtHead == 1)
                {
                    I += 172;
                }
                
                
                //如果有额外信息
                if (deviceMapResult.isExtRes == "1")
                {
                    for (int sRow = 0; sRow < deviceMapResult.linesize; sRow++)
                    {
                        for (int sCol = 0; sCol < deviceMapResult.rowsize; sCol++)
                        {
                            for (int j = 1; j <= 4; j += 2)
                            {
                                long tmpexRes = 0;
                                string tmp1ExRes = string.Empty;
                                for (int posexRes = I; posexRes <= I + 1; posexRes++)
                                {
                                    tmp1ExRes += StringUtils.Dec2Hex(aryContent[posexRes]);
                                }
                                tmpexRes = Convert.ToInt64(tmp1ExRes, 16);
                                string texRes = StringUtils.DEC_to_BIN(tmpexRes).PadLeft(16, '0');
                                switch (j)
                                {
                                    case 1:
                                        if (deviceMapResult.version == 2 || deviceMapResult.version == 3)
                                        {
                                            deviceMapResult.excategoryData[sRow,sCol] = StringUtils.DEC_to_BIN(Convert.ToInt64(texRes.Substring(8, 8)));
                                        }
                                        break;
                                    case 3:
                                        if (deviceMapResult.version == 4)
                                        {
                                            deviceMapResult.excategoryData[sRow,sCol] = StringUtils.DEC_to_BIN(Convert.ToInt64(texRes.Substring(6, 10)));
                                        }
                                        if (deviceMapResult.version == 5)
                                        {
                                            deviceMapResult.excategoryData[sRow,sCol]  = StringUtils.DEC_to_BIN(Convert.ToInt64(texRes.Substring(6, 10)));
                                        }
                                        if (deviceMapResult.version == 7)
                                        {
                                            deviceMapResult.excategoryData[sRow,sCol] = StringUtils.DEC_to_BIN(Convert.ToInt64(texRes.Substring(2, 14)));
                                        }
                                        break;
                                }
                                I += 2;
                            }
                        }
                    }
                }
                
                

                #endregion


                
                
                
                

                return deviceMapResult;



            }
            
        }



        private static  ReadTsnResult ReadTsn2Map(string aoiTxtPath,long numnewflat)
        {
            if(!File.Exists(aoiTxtPath)) throw new FileNotFoundException("File not found");
            
            ReadTsnResult readTsnResult = new ReadTsnResult();
            
            readTsnResult.AOIMapCategory = new int[5000, 5000];
            readTsnResult.AOIMapData = new int[5000, 5000];
            readTsnResult.pos = 0;
            readTsnResult.scols = 0;
            readTsnResult.srows = 0;
            readTsnResult.numFlat = 0;
            readTsnResult.product_id = String.Empty;
            readTsnResult.ismapData = 0;
            readTsnResult.totFailDie = 0;
            readTsnResult.totPassDie = 0;
            readTsnResult.totTestDie = 0;
            readTsnResult.wafer_id = String.Empty;
            
            int  tmpRow = 1;
            
            
            
            using (StreamReader reader = new StreamReader(aoiTxtPath))
            {
                string? line;
                while ((line =  reader.ReadLine()) != null)
                {
                    
                    Regex regexDevice = new Regex(@"DEVICE:(.*)",RegexOptions.IgnoreCase);
                    Regex regexWafer = new Regex(@"Wafer:(.*)",RegexOptions.IgnoreCase);
                    Regex regexFnloc = new Regex(@"FNLOC:(.*)",RegexOptions.IgnoreCase);
                    Regex regexRowct = new Regex(@"ROWCT:(.*)",RegexOptions.IgnoreCase);
                    Regex regexColct = new Regex(@"COLCT:(.*)",RegexOptions.IgnoreCase);
                    
                    Match match;
                    match = regexDevice.Match(line);

                    if (match.Success)
                    {
                        readTsnResult.product_id = match.Groups[1].Value;
                    }
                    
                    match = regexWafer.Match(line);
                    if (match.Success)
                    {
                        readTsnResult.wafer_id = match.Groups[1].Value;
                    }
                    
                    match = regexFnloc.Match(line);
                    if (match.Success)
                    {
                        readTsnResult.numFlat = StringUtils.DirectionConvert(match.Groups[1].Value);
                    }
                    
                    match = regexRowct.Match(line);
                    if (match.Success)
                    {
                        readTsnResult.srows = int.Parse(match.Groups[1].Value);
                    }
                    
                    match = regexColct.Match(line);
                    if (match.Success)
                    {
                        readTsnResult.scols = int.Parse(match.Groups[1].Value);
                    }


                    if (Regex.IsMatch(line, @"RowData:"))
                    {
                        line = Regex.Replace(line, @"^.*?RowData:", " ");
                        var matches = Regex.Matches(line, @"\S{3}");
                        for (int I = 0; I < matches.Count; I++)
                        {
                            string segment = matches[I].Value.Trim();
                            switch (segment)
                            {
                                case "___":
                                    readTsnResult.AOIMapData[tmpRow, I + 1] = 0;
                                    readTsnResult.AOIMapCategory[tmpRow, I+1] = 0;
                                    break;
                                case "000": 
                                    readTsnResult.AOIMapData[tmpRow, I + 1] = 1;
                                    readTsnResult.AOIMapCategory[tmpRow, I + 1] = 63;
                                    readTsnResult.totPassDie++;
                                    readTsnResult.totTestDie++;
                                    break;
                                default:
                                    readTsnResult.AOIMapData[tmpRow, I + 1] = 2;
                                    readTsnResult.AOIMapCategory[tmpRow, I + 1] = 59;
                                    readTsnResult.totFailDie++;
                                    readTsnResult.totTestDie++;
                                    break;
                            }
                        }
                        tmpRow++;
                    }
                    
                    
                    
                }


                if (readTsnResult.numFlat != numnewflat)
                {
                    long intNewRotationFlat;
                    if (readTsnResult.numFlat >= numnewflat)
                    {
                        intNewRotationFlat = readTsnResult.numFlat - numnewflat;
                    }
                    else
                    {
                        intNewRotationFlat = readTsnResult.numFlat + 360 - numnewflat;
                    }
    
                    int intoldTotRow = readTsnResult.srows;
                    int intoldTotCol = readTsnResult.scols;
                    
                    string[,] stroldMapping = new string[intoldTotRow, intoldTotCol];
                    
                    for (int introw = 0; introw < intoldTotRow; introw++)
                    {
                        for (int intcol = 0; intcol < intoldTotCol; intcol++)
                        {
                            stroldMapping[introw, intcol] = readTsnResult.AOIMapData[introw + 1, intcol + 1].ToString();
                        }
                    }

                    readTsnResult.AOIMapData =  StringUtils.ReRotation(intNewRotationFlat,intoldTotRow,intoldTotCol,stroldMapping);
                    
                    for (int introw = 0; introw < intoldTotRow; introw++)
                    {
                        for (int intcol = 0; intcol < intoldTotCol; intcol++)
                        {
                            stroldMapping[introw, intcol] = readTsnResult.AOIMapCategory[introw + 1, intcol + 1].ToString();
                        }
                    }
                    
                    readTsnResult.AOIMapCategory = StringUtils.ReRotation(intNewRotationFlat,intoldTotRow,intoldTotCol,stroldMapping);
                    


                }
                

                return readTsnResult;

            }
            
            
            
            
        }
        
    }
}

